﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Oracle.DataAccess.Client;
using System.IO;
using System.Text;
using Wicresoft.UnifyShow.Business;
using Microsoft.Practices.Unity;
using Wicresoft.UnifyShow.BusinessImpl;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class ComResourceController : BaseController
    {
        //
        // GET: /AdminDocument/

        private IUser_X user;
        private ICommonResource resource;

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user).Dispose();
            ((IDisposable)resource).Dispose();
        }

        public ComResourceController() { }

        [InjectionConstructor]
        public ComResourceController(IUser_X user, ICommonResource resource)
        {
            this.user = user;
            this.resource = resource;
        }

        [Authorize]
        public ActionResult Admin()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);
            ViewBag.Info = false;

            return View();
        }

        [HttpPost]
        public ActionResult Admin(HttpPostedFileBase mydoc, string name, string keywords)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);


            var fileName = Path.GetFileName(mydoc.FileName);
            var today = DateTime.Today.ToString("yyyyMMdd");
            var guid = Guid.NewGuid().ToString();


            string filePath = Server.MapPath(Path.Combine(ConfigurationManager.AppSettings["CommonResourcePath"], today, guid));

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            string fullFilePath = Path.Combine(filePath, fileName);
            if (System.IO.File.Exists(fullFilePath))
            {
                return Content("文件已经存在");
            }

            mydoc.SaveAs(fullFilePath);

            CommonResourceModel model = new CommonResourceModel()
            {
                FileName = fileName,
                CreateTime = DateTime.Now,
                DName = name,
                Keywords = keywords,
                Submitter = User.Identity.Name,
                Type = "0",//常用资源
                Url = Path.Combine(ConfigurationManager.AppSettings["CommonResourcePath"], today, guid, fileName).Replace('\\', '/')
            };
            try
            {
                var ret = resource.Add(model);
                ViewBag.Info = true;
            }
            catch (Exception ex)
            {
                throw new Exception("操作失败，请重新上传.");

            }



            return View();
        }


        [HttpPost]
        public JsonResult ComResourceList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }
            var list = resource.GetAllCommonResources(out totalCount, page, rows, sort, order);
            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetURL(string id)
        {
            var model = new CommonResourceModel();
            string url = string.Empty;
            if (!string.IsNullOrEmpty(id))
            {
                int myid = Convert.ToInt32(id);
                model = resource.GetByID(myid);
                url = model.Url;
            }
            return Json(Server.UrlEncode(url), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult PostSearchResource(string param, int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            List<CommonResourceModel> list = new List<CommonResourceModel>();
            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            if (string.IsNullOrEmpty(param))
                list = resource.GetAllCommonResources(out totalCount, page, rows, sort, order);
            else
                list = resource.GetPlanByKeywords(out totalCount, param, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Search()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin)
                ViewBag.IsConfigAdmin = false;

            return View();
        }

        public ActionResult DownLoad(int id)
        {
            byte[] files;
            string type, filename;
            DocumentHelper.GetFile(id, out files, out type, out filename);
            return File(files, type, filename);
        }

        public ActionResult ListAdmin()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);

            return PartialView();
        }

        public ActionResult List()
        {
            var model = resource.GetAllComInfo().OrderByDescending(o => o.CreateTime).Take(5).ToList();
            //var model = DocumentHelper.GetList().OrderByDescending(o => o.CreateTime).Take(5).ToList();
            return PartialView(model);
        }

        [HttpPost]
        public JsonResult FileDelete(int ID)
        {
            var file = resource.GetByID(ID);
            if (file != null)
            {
                //本地删除
                string filePath = Server.MapPath(ConfigurationManager.AppSettings["CommonResourcePath"]);
                string fullFilePath = Path.Combine(filePath, file.FileName);
                if (System.IO.File.Exists(fullFilePath))
                {
                    System.IO.File.Delete(fullFilePath);
                }
                //数据库删除
                var result = resource.Delete(ID) ? "OK" : "Error";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            return Json("Error", JsonRequestBehavior.AllowGet);
        }

    }

    public class resourceModel
    {
        public int total;
        public List<CommonResourceModel> rows;
    }
}
